/*
   Copyright (C) 2007 Yen-Ju Chen <yjchenx gmail>

   This application is free software; you can redistribute it and/or 
   modify it under the terms of the MIT license. See COPYING.

*/

#import "HiNetRadioFactory.h"
#import "HRObject.h"

@implementation HiNetRadioFactory

- (void) playHiNetRadio: (id) sender
{
    // open url(mms) with Windows Media Player via AppleScript
    // tell application "Windows Media Player" to open location "mms"
	NSString *s = [NSString stringWithFormat:
			@"tell application \"%s\" to open location \"%@\"",
			"Windows Media Player",
			[_selectedObject valueForProperty: kHiNetRadioMMSProperty]];

    // AppleScript
    NSAppleScript *script = [[NSAppleScript alloc] initWithSource: s];
    NSDictionary *errorInfo;
    NSAppleEventDescriptor *aed = [script executeAndReturnError:&errorInfo];
    if (!aed) 
		NSLog(@"Apple script error: %@", errorInfo);
	DESTROY(script);
}

- (void) didSelectObject: (OKObject *) object
{
	ASSIGN(_selectedObject, object);
}

- (OKGroup *) rootGroup
{
	return _rootGroup;
}

- (NSArray *) propertiesToDisplay
{
	if (_propertiesToDisplay == nil)
	{
		_propertiesToDisplay = [[NSArray alloc] initWithObjects:
			kHiNetRadioNameProperty,
			kHiNetRadioURLProperty,
			nil];
	}
	return _propertiesToDisplay;
}

- (NSMenu *) actionMenu
{
	if (_menu == nil)
	{
		_menu = [[NSMenu alloc] initWithTitle: @"HiNetRadio"];
		id <NSMenuItem> item = [_menu addItemWithTitle: @"Play"
		      action: @selector(playHiNetRadio:)
		      keyEquivalent: @""];
		[item setTarget: self];
	}
	return _menu;
}

- (unsigned int) viewableMask
{
	return KRFactoryItemViewableMask;
}

/* NSObject */
- (id) init
{
	self = [super init];

	NSBundle *bundle = [NSBundle bundleForClass: [self class]];
	NSString *path = [bundle pathForResource: @"station_list" ofType: @"txt"];
	NSFileManager *fm = [NSFileManager defaultManager];
	BOOL isDir = NO;
	if ([fm fileExistsAtPath: path isDirectory: &isDir] == NO ||
	    (isDir == YES))
	{
		NSLog(@"No station_list at %@", path);
		[self dealloc];
		return nil;
	}

	/* Build up root group */
	_rootGroup = [[OKGroup alloc] init];

	NSString *s = [NSString stringWithContentsOfFile: path encoding: NSUTF8StringEncoding error: NULL];
	NSEnumerator *e = [[s componentsSeparatedByString: @"\n"] objectEnumerator];;
	NSString *line = nil;
	while ((line = [e nextObject]))
	{
		if ([line hasPrefix: @"#"])
			continue;
		NSArray *a = [line componentsSeparatedByString: @"=>"];
		if ([a count] != 2)
			continue;
		HRObject *object = [[HRObject alloc] initWithName: [a objectAtIndex: 0]
		                                     url: [a objectAtIndex: 1]];
		[_rootGroup addObject: object];
		DESTROY(object);
	}
	
	[_rootGroup setValue: @"HiNet Radio" forProperty: kOKGroupNameProperty];

	return self;
}

- (void) dealloc
{
	DESTROY(_rootGroup);
	DESTROY(_propertiesToDisplay);
	DESTROY(_menu);
	[super dealloc];
}

@end

